// src/content/index.ts - Content Script
// Injected into web pages to interact with page content

console.log('SideX Content Script loaded');

// Inject CSS for content script UI
const injectCSS = () => {
  const style = document.createElement('style');
  style.textContent = `
    .sidex-highlight {
      background-color: yellow;
      padding: 2px 4px;
      border-radius: 2px;
      box-shadow: 0 0 0 1px rgba(0,0,0,0.1);
    }

    #sidex-btn {
      position: fixed;
      right: 0;
      bottom: calc(100vh / 6);
      z-index: 2147483647;
      width: 36px;
      height: 36px;
      border-radius: 18px 0 0 18px;
      border: none;
      background: linear-gradient(135deg, #6366f1, #8b5cf6);
      color: #fff;
      font-size: 18px;
      cursor: pointer;
      box-shadow: -2px 0 8px rgba(99, 102, 241, 0.3);
      transition: all 0.3s ease;
      user-select: none;
      display: flex;
      align-items: center;
      justify-content: center;
    }

    #sidex-btn:hover {
      transform: translateX(-2px);
      box-shadow: -4px 0 12px rgba(99, 102, 241, 0.4);
      background: #ef4444;
    }

    #sidex-btn:hover:before {
      content: '×';
      position: absolute;
      font-size: 20px;
      font-weight: bold;
      color: #fff;
    }

    #sidex-btn:active {
      transform: scale(0.95);
    }

    .sidex-hint {
      position: fixed;
      right: 50px;
      bottom: calc(100vh / 6 + 18px);
      z-index: 2147483646;
      background: rgba(0, 0, 0, 0.8);
      color: white;
      padding: 8px 12px;
      border-radius: 6px;
      font-size: 12px;
      white-space: nowrap;
      opacity: 0;
      transform: translateX(10px);
      transition: all 0.3s ease;
      pointer-events: none;
    }

    .sidex-hint.show {
      opacity: 1;
      transform: translateX(0);
    }
  `;
  document.head.appendChild(style);
};

// 显示操作提示
const showFloatHint = (message: string) => {
  let hint = document.getElementById('sidex-hint') as HTMLElement;
  if (!hint) {
    hint = document.createElement('div');
    hint.id = 'sidex-hint';
    hint.className = 'sidex-hint';
    document.body.appendChild(hint);
  }

  hint.textContent = message;
  hint.classList.add('show');

  setTimeout(() => {
    hint.classList.remove('show');
  }, 2000);
};

// Create floating button - 严格按照文档要求
const createFloatingButton = () => {
  // 防止重复创建
  if (document.getElementById('sidex-btn')) return;

  const btn = document.createElement('button');
  btn.id = 'sidex-btn';
  btn.textContent = '🤖';
  btn.title = 'Toggle SideX Panel (Alt+S)';

  // 按钮点击事件 - 关键：立即发送消息，保持用户手势同步链
  btn.addEventListener('click', () => {
    console.log('[Float Button] Clicked! Sending TOGGLE message (sync chain)...');

    // 检查扩展上下文是否有效
    if (!chrome?.runtime?.id) {
      console.warn('Extension context invalidated, button will be disabled');
      btn.disabled = true;
      btn.title = 'Extension needs reload';
      showFloatHint('扩展需要重新加载');
      return;
    }

    // 立即发送切换消息，不要任何延迟或异步操作
    chrome.runtime.sendMessage({ cmd: 'TOGGLE' }).then(response => {
      console.log('[Float Button] Toggle response:', response);
      if (response?.success) {
        showFloatHint('正在切换侧边栏...');
      }
    }).catch(error => {
      console.error('[Float Button] Toggle message failed:', error);

      // 检查是否是context invalidated错误
      if (error.message?.includes('Extension context invalidated')) {
        console.warn('Extension context invalidated, disabling button');
        btn.disabled = true;
        btn.title = 'Extension needs reload';
        showFloatHint('扩展上下文失效');
        return;
      }

      // 备选方案：尝试其他消息格式
      try {
        chrome.runtime.sendMessage({ type: 'SIDEX_TOGGLE' });
        showFloatHint('使用备选方案切换...');
      } catch (fallbackError) {
        console.error('All toggle methods failed:', fallbackError);
        showFloatHint('切换失败');
      }
    });
  });

  document.body.appendChild(btn);
  console.log('[Float Button] Injected successfully');
};

// Text selection handler
const handleTextSelection = () => {
  document.addEventListener('mouseup', () => {
    const selection = window.getSelection();
    const selectedText = selection?.toString().trim();

    if (selectedText && selectedText.length > 0) {
      console.log('Text selected:', selectedText);

      // Send selected text to background script
      chrome.runtime.sendMessage({
        action: 'TEXT_SELECTED',
        data: {
          text: selectedText,
          url: window.location.href,
          title: document.title,
        },
        timestamp: Date.now()
      }).catch(() => {
        // 备选方案：发送旧格式
        chrome.runtime.sendMessage({
          type: 'TEXT_SELECTED',
          text: selectedText,
          url: window.location.href,
          title: document.title,
        });
      });
    }
  });
};

// Page analysis function
const analyzePage = () => {
  const pageData = {
    title: document.title,
    url: window.location.href,
    headings: Array.from(document.querySelectorAll('h1, h2, h3, h4, h5, h6'))
      .map(h => ({
        level: parseInt(h.tagName.charAt(1)),
        text: h.textContent?.trim() || '',
        id: h.id
      }))
      .filter(h => h.text),
    links: Array.from(document.querySelectorAll('a[href]'))
      .slice(0, 20)
      .map(a => ({
        text: a.textContent?.trim() || '',
        href: a.getAttribute('href') || '',
        title: a.getAttribute('title'),
        external: !a.getAttribute('href')?.startsWith(window.location.origin)
      }))
      .filter(link => link.text && link.href),
    images: Array.from(document.querySelectorAll('img[src]'))
      .slice(0, 10)
      .map(img => ({
        src: img.getAttribute('src') || '',
        alt: img.getAttribute('alt') || '',
        title: img.getAttribute('title'),
        width: (img as HTMLImageElement).naturalWidth,
        height: (img as HTMLImageElement).naturalHeight
      })),
    wordCount: document.body.textContent?.split(/\s+/).filter(word => word.length > 0).length || 0,
    metadata: {
      description: document.querySelector('meta[name="description"]')?.getAttribute('content') || '',
      keywords: document.querySelector('meta[name="keywords"]')?.getAttribute('content') || '',
      author: document.querySelector('meta[name="author"]')?.getAttribute('content') || '',
      viewport: document.querySelector('meta[name="viewport"]')?.getAttribute('content') || ''
    }
  };

  return pageData;
};

// Message listener for communication with background/side panel
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  console.log('Content script received message:', message);

  // 支持新旧消息格式
  const action = message.action || message.type;
  const data = message.data || message;

  switch (action) {
    case 'ANALYZE_PAGE': {
      const analysisResult = analyzePage();
      sendResponse({
        success: true,
        ...analysisResult
      });
      break;
    }

    case 'HIGHLIGHT_TEXT': {
      const textToHighlight = data.text || message.text;
      if (textToHighlight) {
        highlightText(textToHighlight);
        sendResponse({ success: true });
      } else {
        sendResponse({ success: false, error: 'No text provided' });
      }
      break;
    }

    case 'GET_SELECTED_TEXT': {
      const selection = window.getSelection();
      sendResponse({
        success: true,
        text: selection?.toString() || '',
        range: selection?.rangeCount ? selection.getRangeAt(0) : null,
      });
      break;
    }

    default:
      console.log('Unknown message type:', action);
      sendResponse({ success: false, error: 'Unknown message type' });
  }

  return true;
});

// Text highlighting function
const highlightText = (searchText: string) => {
  const walker = document.createTreeWalker(
    document.body,
    NodeFilter.SHOW_TEXT,
    {
      acceptNode: function(node) {
        // 跳过已经高亮的元素和脚本/样式元素
        if (node.parentElement?.classList?.contains('sidex-highlight') ||
            node.parentElement?.tagName === 'SCRIPT' ||
            node.parentElement?.tagName === 'STYLE') {
          return NodeFilter.FILTER_REJECT;
        }
        return NodeFilter.FILTER_ACCEPT;
      }
    }
  );

  const textNodes: Text[] = [];
  let node;

  while ((node = walker.nextNode())) {
    textNodes.push(node as Text);
  }

  textNodes.forEach(textNode => {
    const parent = textNode.parentNode;
    if (parent && textNode.textContent && textNode.textContent.toLowerCase().includes(searchText.toLowerCase())) {
      const regex = new RegExp(escapeRegExp(searchText), 'gi');

      if (regex.test(textNode.textContent)) {
        const highlightedHTML = textNode.textContent.replace(
          regex,
          '<span class="sidex-highlight">$&</span>'
        );

        const wrapper = document.createElement('span');
        wrapper.innerHTML = highlightedHTML;
        parent.replaceChild(wrapper, textNode);
      }
    }
  });
};

// Escape special regex characters
const escapeRegExp = (string: string) => {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
};

// Initialize content script
const init = () => {
  // Only run on main frame, not iframes
  if (window.self === window.top) {
    injectCSS();
    createFloatingButton();
    handleTextSelection();

    // Send page load event to background
    chrome.runtime.sendMessage({
      action: 'PAGE_LOADED',
      data: analyzePage(),
      timestamp: Date.now()
    }).catch(() => {
      // 备选方案：发送旧格式
      chrome.runtime.sendMessage({
        type: 'PAGE_LOADED',
        data: analyzePage(),
      });
    });

    console.log('SideX Content Script initialized');
  }
};

// Wait for DOM to be ready
if (document.readyState === 'loading') {
  document.addEventListener('DOMContentLoaded', init);
} else {
  init();
}